const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");

const HORIZONTAL_MARGIN = 50;
const VERTICAL_MARGIN = 50;

function drawAxis() {
    context.save();
    context.fillStyle = "black";
    context.lineWidth = 0.5;
    drawVerticalAxis();
    drawHorizontalAxis();
    drawVerticalLabel();
    drawHorizontalLabel();
    context.restore();
}

function drawVerticalAxis() {
    context.beginPath();
    context.moveTo(
        HORIZONTAL_MARGIN + 0.5,
        canvas.height - VERTICAL_MARGIN + 0.5
    );
    context.lineTo(HORIZONTAL_MARGIN + 0.5, VERTICAL_MARGIN + 0.5);
    context.stroke();
}

function drawHorizontalAxis() {
    context.beginPath();
    context.moveTo(
        HORIZONTAL_MARGIN + 0.5,
        canvas.width - VERTICAL_MARGIN + 0.5
    );
    context.lineTo(
        canvas.width - HORIZONTAL_MARGIN,
        canvas.width - VERTICAL_MARGIN + 0.5
    );
    context.stroke();
}

function drawVerticalLabel() {
    const step = 10;
    const totalLabel = (canvas.height - VERTICAL_MARGIN * 2) / step;
    for (let i = 1; i < totalLabel; i++) {
        const offset = i % 5 === 0 ? 5 : 0;
        context.beginPath();
        context.moveTo(
            HORIZONTAL_MARGIN - 5 - offset + 0.5,
            i * step + VERTICAL_MARGIN + 0.5
        );
        context.lineTo(
            HORIZONTAL_MARGIN - 5 + step + offset + 0.5,
            i * step + VERTICAL_MARGIN + 0.5
        );
        context.stroke();
        if (offset) {
            context.textAlign = "right";
            context.textBaseline = "middle";
            context.font = "14px Monaco";
            context.fillText(
                i,
                HORIZONTAL_MARGIN - 20,
                i * step + VERTICAL_MARGIN
            );
        }
    }
}

function drawHorizontalLabel() {
    const step = 10;
    const totalLabel = (canvas.width - HORIZONTAL_MARGIN * 2) / step;
    for (let i = 1; i < totalLabel; i++) {
        const offset = i % 5 === 0 ? 5 : 0;
        context.beginPath();
        context.moveTo(
            i * step + HORIZONTAL_MARGIN + 0.5,
            canvas.height - VERTICAL_MARGIN - 5 - offset + 0.5
        );
        context.lineTo(
            i * step + HORIZONTAL_MARGIN + 0.5,
            canvas.height - VERTICAL_MARGIN - 5 + step + offset + 0.5
        );
        context.stroke();

        if (offset) {
            context.textAlign = "center";
            context.textBaseAlign = "top";
            context.font = "14px Monaco";
            context.fillText(
                i,
                i * step + HORIZONTAL_MARGIN,
                canvas.height - VERTICAL_MARGIN + 25
            );
        }
    }
}

drawAxis();
